<template>

  <div class="app-container">
    <a-card style="margin-bottom: 16px">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="单位" prop="schoolId">
          <el-select @change="onchangeSchool" clearable v-model="queryParams.schoolId" placeholder="请选择">
            <el-option
                v-for="item in schoolList"
                :key="item.id"
                :label="item.unitName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="组别" prop="schoolId">
          <el-select @change="onchangeGroup" clearable v-model="queryParams.groupId" placeholder="请选择">
            <el-option
                v-for="item in groupList"
                :key="item.id"
                :label="item.gropuName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item style="flex: 1">
          <el-button type="primary" icon="Search" @click="getList">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>

        <el-form-item style="flex: 1">

          <el-button type="primary" icon="Present" @click="outputShoujiWord">导出手记表</el-button>
          <el-button type="primary" icon="Present" @click="outputShoujiWord2">导出手记表2</el-button>
          <el-button type="primary" icon="Present" @click="outputScoreWord(false)">导出成绩单（无姓名）</el-button>
          <el-button type="primary" icon="Present" @click="outputScoreWord(true)">导出成绩单</el-button>
          <el-button type="primary" icon="Present" @click="outputExcel">导出登分表</el-button>
          <el-button type="primary" icon="Present" @click="inputScoreExcel">导入登分表</el-button>
        </el-form-item>
      </el-form>
    </a-card>

    <el-row :gutter="20">
      <!--部门数据-->
      <el-col style="height: 100%" :span="6" :xs="24">
        <a-card title="项目选择">
          <div style="display: flex;flex-direction: column;flex: 1">
            <div style="" class="head-container">
              <el-input
                  v-model="subName"
                  placeholder="请输入项目名称"
                  clearable
                  prefix-icon="Search"
                  style="margin-bottom: 20px"
              />
            </div>
            <el-tree
                style="height: 480px;overflow-y: scroll"
                :data="subjectOptions"
                :props="{ label: 'label', children: 'children' }"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="deptTreeRef"
                node-key="id"
                highlight-current
                default-expand-all
                @node-click="handleNodeClick"
            />
          </div>
        </a-card>
      </el-col>
      <!--用户数据-->
      <el-col :span="18" :xs="24">
        <a-card style="" title="成绩录入" v-if="selectSubject.type!=null">
          <template #extra>
            <a-button @click="importRes" v-if="selectSubject.code=='lsmp'">导入res</a-button>
          </template>
          <el-table
              style="height: 480px"
              v-loading="tableLoading"
              row-key="objectId"
              :expand-row-keys="expandedRowKeys"
              :data="orchestrateList">
            <el-table-column type="expand">
              <template #default="props">

                <el-table :data="props.row.subjectWithItem.baseSubItemList" :border="childBorder">
                  <el-table-column width="100" :label="props.row.subjectWithItem.baseSubItemList[0].itemName" prop=""/>
                  <el-table-column width="200" label="成绩项">
                    <template #default="scope">
                      {{ scope.$index == 0 ? '总分' : scope.row.itemName }}
                    </template>
                  </el-table-column>
                  <el-table-column width="160" v-if="props.row.subjectWithItem.count>=1" label="成绩1" prop="state">
                    <template #default="scope">
                      <div style="display: flex;justify-content: space-between">
                        <span v-if="scope.row.scoreHashMap['1']" style="width: 120px;display: flex;align-items: center">
                          <span v-if="scope.row.scoreHashMap['1'].rawScore" style="flex: 1;text-align: center">
                            {{ scope.row.scoreHashMap['1'].rawScore }}
                          </span>
                          <span v-else style="flex: 1;text-align: center">
                            --
                          </span>
                          <span style="flex: 1;text-align: center">
                            |
                          </span>
                          <span style="flex: 1;text-align: center">
                            {{ scope.row.scoreHashMap['1'].conversionScore }}
                          </span>

                        </span>
                        <span v-else style="flex: 1;text-align: center">
                          --
                        </span>
                        <a-button @click="showEidScore(props.row,1,scope.row)" size="small">打分</a-button>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column width="160" v-if="props.row.subjectWithItem.count>=2" label="成绩2" prop="state">
                    <template #default="scope">
                      <div style="display: flex;justify-content: space-between">
                         <span v-if="scope.row.scoreHashMap['2']"
                               style="width: 120px;display: flex;align-items: center">
                          <span v-if="scope.row.scoreHashMap['2'].rawScore" style="flex: 1;text-align: center">
                            {{ scope.row.scoreHashMap['2'].rawScore }}
                          </span>
                          <span v-else style="flex: 1;text-align: center">
                            --
                          </span>
                          <span style="flex: 1;text-align: center">
                            |
                          </span>
                          <span style="flex: 1;text-align: center">
                            {{ scope.row.scoreHashMap['2'].conversionScore }}
                          </span>

                        </span>
                        <span v-else style="flex: 1;text-align: center">
                          --
                        </span>
                        <a-button @click="showEidScore(props.row,2,scope.row)" size="small">打分</a-button>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column width="160" v-if="props.row.subjectWithItem.count>=3" label="成绩3" prop="state">
                    <template #default="scope">
                      <div style="display: flex;justify-content: space-between">
                         <span v-if="scope.row.scoreHashMap['3']"
                               style="width: 120px;display: flex;align-items: center">
                          <span v-if="scope.row.scoreHashMap['3'].rawScore" style="flex: 1;text-align: center">
                            {{ scope.row.scoreHashMap['3'].rawScore }}
                          </span>
                          <span v-else style="flex: 1;text-align: center">
                            --
                          </span>
                          <span style="flex: 1;text-align: center">
                            |
                          </span>
                          <span style="flex: 1;text-align: center">
                            {{ scope.row.scoreHashMap['3'].conversionScore }}
                          </span>

                        </span>
                        <span v-else style="flex: 1;text-align: center">
                          --
                        </span>
                        <a-button @click="showEidScore(props.row,3,scope.row)" size="small">打分</a-button>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label=" " align="center" prop=""/>
                  <el-table-column width="160" label="最终成绩" prop="state">
                    <template #default="scope">
                      <div style="display: flex;justify-content: space-between">
                        <span style="width: 120px">
                            {{
                            scope.row.scoreHashMap['0'] == null ? '--' : scope.row.scoreHashMap['0'].conversionScore
                          }}
                        </span>

                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>

            <el-table-column v-hasPermi="['business:user:edit']" width="160" label="名称" align="center" prop="name"/>
            <el-table-column v-if="selectSubject.type==1 || selectSubject.lottery==1" label="性别" align="center"
                             prop="sex">
              <template #default="scope">
                <dict-tag :options="teacher_sex_type" :value="scope.row.sex"/>
              </template>
            </el-table-column>

            <el-table-column v-if="selectSubject.lottery!=1" label="赛中编号" align="center" prop="no"/>
            <el-table-column label="组别" align="center" prop="groupName"/>
            <el-table-column v-if="selectSubject.code=='lsmp'" label="序号" align="center" prop="xh"/>

            <el-table-column v-if="selectSubject.lottery==1" label="项目" align="center" prop="subName"/>


            <el-table-column v-else label="成绩" align="center" prop="xh">
              <template #default="scope">
                <span
                    :style="{color:scope.row.subjectWithItem.baseScoreMap['0']!=null && scope.row.subjectWithItem.baseScoreMap['0'].confirm?'red':''}"
                    v-if="scope.row.subjectWithItem">
                  {{
                    scope.row.subjectWithItem.baseScoreMap['0'] == null ? '' : scope.row.subjectWithItem.baseScoreMap['0'].conversionScore
                  }}
                </span>
              </template>
            </el-table-column>

            <el-table-column v-hasPermi="['business:user:edit']" width="160" label="单位" align="center"
                             prop="unitName">
              <template #default="scope">
                <span v-if="selectSubject.type == 1">
                  {{ scope.row.unitName }}
                </span>
                <span v-if="selectSubject.type == 2">
                  {{ scope.row.name }}
                </span>
              </template>
            </el-table-column>

            <el-table-column fixed="right" width="200" label="操作" align="center"
                             class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary" icon="Upload" @click="stuReady(scope.row)"
                           v-hasPermi="['business:score:edit']">打分
                </el-button>

                <el-button link type="primary" icon="View" @click="showStuScore(scope.row)"
                           v-hasPermi="['business:score:edit']">显示
                </el-button>

                <el-button link type="primary" icon="Edit"
                           @click="showEidScore(scope.row,1,scope.row.subjectWithItem.baseSubItemList[0])"
                           v-hasPermi="['business:score:edit']">
                  修改
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
              v-show="total>0"
              :total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="getList"
          />
        </a-card>
        <a-card v-else>
          <a-empty>
            <template #description>
              <span>
                无需操作
              </span>
            </template>
          </a-empty>
        </a-card>
      </el-col>
    </el-row>

    <a-modal centered v-model:open="editShow" title="编辑">
      <el-form :model="updateItem" label-width="80px">
        <el-form-item label="赛中编号" prop="no">
          <el-input v-model="updateItem.no" placeholder="请输入赛中编号"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmUpdate">确 定</el-button>
          <el-button @click="editShow=false">取 消</el-button>
        </div>
      </template>
    </a-modal>

    <a-modal v-if="selectItem" :footer="null" centered v-model:open="editScoreShow"
             :title="selectItem==null?'打分面板':selectItem.itemName + '打分面板'" @ok="handleOk">
      <div style="display: flex;flex-direction: column">
        <div style="display: flex;flex-direction: row">
          <a-input size="large" v-model:value="inputValue"
                   :placeholder="'请输入' + selectItem.minScore + '-' +selectItem.maxScore + '分值'"/>
          <a-select size="large" style="width: 90px" v-model:value="inputValue">
            <a-select-option :value="-1">犯规</a-select-option>
            <a-select-option :value="-2">弃赛</a-select-option>
          </a-select>
        </div>
        <div style="margin-top: 8px" class="keyboard">
          <div @click="input('1')" class="key">
            <div>1</div>
          </div>
          <div @click="input('2')" class="key">
            <div>2</div>
          </div>
          <div @click="input('3')" class="key">
            <div>3</div>
          </div>
          <div @click="input('<')" class="key">
            <div>
              <ArrowLeftOutlined/>
            </div>
          </div>
          <div @click="input('4')" class="key">
            <div>4</div>
          </div>
          <div @click="input('5')" class="key">
            <div>5</div>
          </div>
          <div @click="input('6')" class="key">
            <div>6</div>
          </div>
          <div @click="input('-')" class="key">
            <div>-</div>
          </div>
          <div @click="input('7')" class="key">
            <div>7</div>
          </div>
          <div @click="input('8')" class="key">
            <div>8</div>
          </div>
          <div @click="input('9')" class="key">
            <div>9</div>
          </div>
          <div @click="input('cancel')" class="key">
            <div style="background: #ff899b">取消</div>
          </div>
          <div @click="input(':')" class="key">
            <div>：</div>
          </div>
          <div @click="input('.')" class="key">
            <div>.</div>
          </div>
          <div @click="input('0')" class="key">
            <div>0</div>
          </div>
          <div @click="input('confirm')" class="key">
            <div style="background: #3dbaff">确定</div>
          </div>
        </div>
      </div>
    </a-modal>

    <a-modal width="800" :footer="null" centered v-model:open="importResShow"
             title="导入成绩">
      <div style="display: flex;flex-direction: column;height: 480px;display: flex;flex-direction: column">

        <div style="display: flex;justify-content: end;align-items: center;margin-bottom: 16px">
          <div>组别：</div>
          <a-select @change="handleChange" v-model:value="selectLsmpZb" style="width: 120px">
            <a-select-option v-for="(item,index) in zbList" :value="item">{{ item }}组</a-select-option>
          </a-select>
        </div>

        <div style="flex: 1">

          <el-table
              row-key="objectId"
              :data="updateLsmpList">

            <el-table-column width="160" label="名称" align="center" prop="name"/>
            <el-table-column v-if="selectSubject.type==1 || selectSubject.lottery==1" label="性别" align="center"
                             prop="sex">
              <template #default="scope">
                <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
              </template>
            </el-table-column>

            <el-table-column width="160" label="单位" align="center" prop="unitName">
              <template #default="scope">
                <span v-if="selectSubject.type == 1">
                  {{ scope.row.unitName }}
                </span>
                <span v-if="selectSubject.type == 2">
                  {{ scope.row.name }}
                </span>
              </template>
            </el-table-column>

            <el-table-column v-if="selectSubject.lottery!=1" label="赛中编号" align="center" prop="no"/>
            <el-table-column v-if="selectSubject.code=='lsmp'" label="组别" align="center" prop="zb"/>
            <el-table-column v-if="selectSubject.code=='lsmp'" label="序号" align="center" prop="xh"/>

            <el-table-column v-if="selectSubject.lottery==1" label="项目" align="center" prop="subName"/>
            <el-table-column width="120" v-else label="成绩" align="center">
              <template #default="scope">
                <span v-if="!scope.row.updateScore || scope.row.updateScore==-1||scope.row.updateScore==-2">
                  <a-select style="width: 90px" v-model:value="scope.row.updateScore">
                    <a-select-option value="-1">犯规</a-select-option>
                    <a-select-option value="-2">弃赛</a-select-option>
                  </a-select>
                </span>
                <span v-else>{{ scope.row.updateScore }}</span>
              </template>
            </el-table-column>


          </el-table>
        </div>
        <div style="display:flex;justify-content: end">
          <a-button @click="selectRes" style="margin-right: 16px">导入</a-button>
          <a-button style="margin-right: 16px">取消</a-button>
          <a-button @click="updateLsmpScore">提交</a-button>
        </div>
      </div>
    </a-modal>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <!--        <template #tip>-->
        <!--          <div class="el-upload__tip text-center">-->
        <!--            <div class="el-upload__tip">-->
        <!--              <el-checkbox v-model="upload.updateSupport"/>-->
        <!--              是否更新已经存在的用户数据-->
        <!--            </div>-->
        <!--            <span>仅允许导入xls、xlsx格式文件。</span>-->
        <!--            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"-->
        <!--                     @click="importTemplate">下载模板-->
        <!--            </el-link>-->
        <!--          </div>-->
        <!--        </template>-->
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <input
        multiple
        type="file"
        name="filename"
        id="resChoice"
        style="display: none"
        @change="changeFile"
    />
  </div>


</template>

<script>
import {deptTreeSelect} from "@/api/business/subject";
import {list, update, lottery,} from "@/api/business/orchestrate";
import {getScoreItem, updateScore, stuReady, getAllLsmpZb, showStuInfo} from "@/api/business/score";
import {ref, watch} from 'vue';
import {listSchool} from "@/api/business/school.js";
import {AddLocation} from "@element-plus/icons-vue"
import {updateStuScore} from "../../../api/business/score";
import {message} from 'ant-design-vue';
import {getToken} from "@/utils/auth.js";
import {listUnit} from "@/api/business/unit";
import {listGroup} from "@/api/business/group.js";

export default {
  name: "LotteryPage",
  data() {
    const {proxy} = getCurrentInstance();
    const subName = ref("");
    const {base_confirm_status, teacher_sex_type} = proxy.useDict('base_confirm_status', 'teacher_sex_type');
    watch(subName, (newVal, oldVal) => {
      this.$refs["deptTreeRef"].filter(newVal);
    });
    let queryParams = {
      subId: null,
      pageNum: 1,
      pageSize: 10,
      schoolId: null,
      no: null,
      avatarSrc: null,
      name: null,
      stuNo: null,
      className: null,
      nation: null,
      sex: null,
      birth: null,
      birthPlace: null,
      cardId: null,
      mailAddress: null,
      mobile: null,
      oneConfirm: null,
      oneConfirmTime: null,
      twoConfirm: null,
      twoConfirmTime: null,
      editShow: true,
      schoolList: [],
      tableLoading: false,

    };
    const channel = new BroadcastChannel('enterScore');
    /*** 用户导入参数 */
    const upload = reactive({
      // 是否显示弹出层（用户导入）
      open: false,
      // 弹出层标题（用户导入）
      title: "",
      // 是否禁用上传
      isUploading: false,
      // 是否更新已经存在的用户数据
      updateSupport: 0,
      // 设置上传的请求头部
      headers: {Authorization: "Bearer " + getToken()},
      // 上传的地址
      url: import.meta.env.VITE_APP_BASE_API + "/business/score/inputScoreExcel"
    });
    return {
      teacher_sex_type,
      showSearch: true,
      subjectOptions: [],
      subName,
      selectSubject: {},
      orchestrateList: [],
      queryParams,
      total: 0,
      form: {},
      editShow: false,
      updateItem: {},
      editScoreShow: false,
      inputValue: '',
      selectItem: null,
      expandedRowKeys: null,
      channel,
      proxy,
      upload,
      importResShow: false,
      zbList: [],
      selectLsmpZb: null,
      updateLsmpList: [],
      groupList: [],
    }

  },
  mounted() {
    this.getSchoolList();
    this.getGroupList();
    this.getDeptTree();
    /** 根据名称筛选部门树 */
    this.channel.postMessage('message');
    // setTimeout(() => {
    //   if (this.selectSubject != {}) {
    //     this.getList();
    //   }
    // }, 2000)
  },
  // watch(){
  //
  // },
  beforeUnmount() {

  },

  methods: {
    onchangeGroup(){
      this.getList();
    },
    importRes() {
      let that = this;
      this.importResShow = true;
      getAllLsmpZb().then(response => {
        console.log(response);
        that.zbList = response.data;
      });
    },
    selectRes() {
      document.getElementById("resChoice").click();
    },
    handleChange() {
      let that = this;
      this.queryParams.zb = this.selectLsmpZb;
      getScoreItem(this.queryParams).then(response => {
        console.log(response)
        that.updateLsmpList = response.rows;
        // message.success({content: '上传成功!', key, duration: 2});
      }).catch(err => {

      });
    },
    async changeFile() {
      const fu = document.getElementById("resChoice");
      if (fu == null) {
        console.log("null");
        return;
      }
      console.log(fu.files);
      let fileScore = null;
      for (let i = 0; i < fu.files.length; i++) {
        let fi = fu.files[i];
        if (fi.name.endsWith("res")) {
          fileScore = fu.files[i]
        }
      }
      if (fileScore == null) {
        this.$message.warning("无成绩文件res");
        return;
      }
      let scoreList = await this.getScoreList(fileScore);
      console.info(scoreList)
      for (let i = 0; i < scoreList.length; i++) {
        console.log(scoreList[i]);
        for (let j = 0; j < this.updateLsmpList.length; j++) {
          if (this.updateLsmpList[j].xh == scoreList[i].bh) {
            this.updateLsmpList[j].updateScore = scoreList[i].score;
          }
        }
      }
      fu.value = '';
    },
    async updateLsmpScore() {
      const key = 'updatable';
      message.loading('上传中', key, 0);
      for (let j = 0; j < this.updateLsmpList.length; j++) {
        let that = this;
        let body = {
          objectType: this.updateLsmpList[j].objectType,
          objectId: this.updateLsmpList[j].objectId,
          subId: this.updateLsmpList[j].subId,
          count: 1,
          itemNo: 0,
          rawScore: this.updateLsmpList[j].updateScore,
        }


        await updateStuScore(body).then(response => {
          console.log(response);

        });
      }
      this.updateLsmpList = [];
      this.importResShow = false;
      message.success({content: '上传成功!', key, duration: 2});
    },
    outputShoujiWord() {
      let that = this;
      this.proxy.download('business/score/outputShoujiWord', {
        subId: this.queryParams.subId,
        groupId: this.selectItem.groupId,
      }, `手记表${new Date().getTime()}.docx`)
    },
    outputShoujiWord2() {
      let that = this;
      this.proxy.download('business/score/outputShoujiWord2', {
        subId: this.queryParams.subId,
        groupId: this.queryParams.groupId,
      }, `手记表${new Date().getTime()}.docx`)
    },
    outputScoreWord(hasName) {
      let that = this;
      this.proxy.download('business/score/outputScoreWord', {
        subId: this.queryParams.subId,
        hasName: hasName,
        groupId: this.queryParams.groupId,
      }, `成绩单${new Date().getTime()}.docx`)
    },
    outputExcel() {
      let that = this;
      this.proxy.download('business/score/outputScoreExcel', {
        subId: this.queryParams.subId,
        groupId: this.queryParams.groupId,
      }, `登分表${new Date().getTime()}.xlsx`)
    },
    inputScoreExcel() {
      this.upload.title = "成绩导入";
      this.upload.open = true;
    },
    /**文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.proxy.$refs["uploadRef"].handleRemove(file);
      this.proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },

    /** 提交上传文件 */
    submitFileForm() {
      this.proxy.$refs["uploadRef"].submit();
    },
    input(char) {
      if (char === '<') {
        if (this.inputValue.length >= 1) {
          this.inputValue = this.inputValue.slice(0, -1);
        }

      } else if (char === 'cancel') {
        this.inputValue = '';
        this.editScoreShow = false;
        this.selectItem = null;
      } else if (char === 'confirm') {
        if (this.inputValue == '') {
          return;
        }
        this.confirmScore();
      } else {
        this.inputValue = this.inputValue + char;
      }
    },
    showEidScore(e, count, subItem) {
      this.selectItem = e;
      this.selectItem.count = count;
      this.selectItem.itemNo = subItem.itemNo;
      this.selectItem.itemName = subItem.itemName;
      this.selectItem.minScore = subItem.minScore;
      this.selectItem.maxScore = subItem.maxScore;
      this.editScoreShow = true;
    },
    confirmScore() {
      let that = this;
      let body = {
        objectType: this.selectItem.objectType,
        objectId: this.selectItem.objectId,
        groupId: this.selectItem.groupId,
        subId: this.selectItem.subId,
        count: this.selectItem.count,
        itemNo: this.selectItem.itemNo,
        rawScore: this.inputValue,
      }
      const key = 'updatable';
      message.loading('上传中', key, 0);
      updateStuScore(body).then(response => {
        console.log(response);
        that.inputValue = '';
        that.editScoreShow = false;
        that.selectItem = null;
        that.getList();
        message.success({content: '上传成功!', key, duration: 2});
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      let that = this;
      deptTreeSelect().then(response => {
        console.log(response)
        that.subjectOptions = response.data;
      });
    },
    /** 通过条件过滤节点  */
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 节点单击事件 */
    handleNodeClick(data) {
      let that = this;
      this.selectSubject = data.baseSubject;
      this.queryParams.subId = data.baseSubject.id;
      this.queryParams.subName = data.baseSubject.name;
      this.queryParams.type = data.baseSubject.type;
      that.orchestrateList = [];
      this.getList();
    },
    getList() {
      let that = this;
      this.tableLoading = true;
      getScoreItem(this.queryParams).then(response => {
        console.log(response)
        that.orchestrateList = response.rows;
        that.total = response.total;
        that.tableLoading = false;
        // message.success({content: '上传成功!', key, duration: 2});
      }).catch(err => {
        that.orchestrateList = [];
        that.tableLoading = false;
        that.total = 0;
      });
    },
    handleUpdate(item) {
      console.log(item);
      this.updateItem = item;
      this.editShow = true;
    },
    showStuScore(item) {
      let conversionScore = '';
      if (item.subjectWithItem != null) {
        if (item.subjectWithItem.baseScoreMap['0'] != null) {
          conversionScore = item.subjectWithItem.baseScoreMap['0'].conversionScore;
        }
      }
      let sendInfo = {
        type: 'score',
        name: item.name,
        no: item.no,
        subName: this.queryParams.subName,
        objectType: item.objectType,
        objectId: item.objectId,
        subId: item.subId,
        groupId: this.queryParams.groupId,
      }
      this.channel.postMessage(sendInfo);
      showStuInfo(sendInfo).then(response => {
        console.log(response)
        this.getList();
      })
      // stuReady(item).then(response => {
      //   console.log(response)
      // })

    },
    async stuReady(item) {
      console.log(JSON.stringify(item));
      let sendInfo = {
        type: 'ready',
        name: item.name,
        no: item.no,
        objectId: item.objectId,
        subId: item.subId,
        subName: this.queryParams.subName,
        objectType: item.objectType,
      }
      this.channel.postMessage(sendInfo);

      stuReady(item).then(response => {
        console.log(response)
      })
    },
    confirmUpdate() {
      let that = this;
      update(this.updateItem).then(response => {
        that.editShow = false;
        that.getList();
        console.log(response)
      })
    },
    /** 查询学校列表 */
    getSchoolList() {
      let that = this;
      listUnit(
          {pageSize: 0}
      ).then(response => {
        that.schoolList = response.rows;
      });
    },
    keepTwoDecimalFull(num) {
      var result = parseFloat(num);
      if (isNaN(result)) {
        alert('传递参数错误，请检查！');
        return false;
      }
      result = Math.round(num * 100) / 100;
      var s_x = result.toString(); //将数字转换为字符串

      var pos_decimal = s_x.indexOf('.'); //小数点的索引值


      // 当整数时，pos\_decimal=-1 自动补0
      if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += '.';
      }

      // 当数字的长度< 小数点索引+2时，补0
      while (s_x.length <= pos_decimal + 2) {
        s_x += '0';
      }
      return s_x;
    },
    getGroupList() {
      let that = this;
      listGroup(
          {pageSize: 0}
      ).then(response => {
        that.groupList = response.rows;
      });
    },
    getScoreList(file) {
      let that = this;
      return new Promise(resolve => {
        let reader = new FileReader();
        reader.onload = function (event) {
          let result = [];
          let content = event.target.result;
          let lines = content.split('\n');
          for (let i = 0; i < lines.length; i++) {
            if (lines[i].trim() === "") continue;
            let line = lines[i].replaceAll('  ', ' ')
            let str = line.split(' ');
            if (str.length !== 4) {
              continue;
            }
            // score.setBh(Integer.parseInt(s[2]));
            // score.setScore(s[3]);
            // 001 000 002 0:14:05.1010
            let scoreS = str[3].split(':');
            let obj = {
              id: str[0],
              bh: parseInt(str[2]),
              score: that.keepTwoDecimalFull(Number.parseFloat(scoreS[2].trim())),
            }
            result.push(obj);
          }
          resolve(result);
          content = null;
        };
        reader.readAsText(file);
      });
    }
  }
}
</script>

<style>
.keyboard {
  display: flex;
  flex-wrap: wrap;
  border-radius: 16px;
  background: #ececec;
}

.key {
  height: 64px;
  flex-basis: 25%;
  padding: 8px;
}

.key div {
  border-radius: 8px;
  background: white;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  font-weight: bolder;
}

.key div:hover {
  cursor: pointer;
}

.key div:active {
  background: #23b3ff;
}
</style>
